package com.suep.business.service.impl;

import com.suep.business.domain.Coupon;
import com.suep.business.domain.Order;
import com.suep.business.dto.CouponDTO;
import com.suep.business.mapper.CouponMapper;
import com.suep.business.service.ICouponService;
import com.suep.system.utils.RequestAttributeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CouponServiceImpl implements ICouponService {
    @Autowired
    private CouponMapper couponMapper;

    @Override
    public void receive(Integer userId, CouponDTO couponDTO) {
        Integer couponId=couponDTO.getId();
        Coupon coupon=couponMapper.selectCouponById(couponId);
        coupon.setRemainCount(coupon.getRemainCount()-1);
        couponMapper.updateCouponById(coupon);
        couponMapper.insertUserAndCoupon(userId,couponId);
    }
    @Override
    public Integer useMyCoupon(Integer userId){
        return couponMapper.useMyCoupon(userId,LocalDateTime.now());
    }
    @Override
    public List<CouponDTO> selectMyCoupon(Integer userId){
        return couponMapper.selectMyCoupon(userId);
    }

    public void use(HttpServletRequest request){
        Integer userId=RequestAttributeUtil.getUserIdFromRequest(request);

    }


    //    DTO传递连表查询信息
    @Override
    public List<CouponDTO> selectAllCoupon(){
       return couponMapper.selectAllCoupon(LocalDateTime.now());
    }

    @Override
    public Integer insertCoupon(Coupon coupon) {
        return couponMapper.insertCoupon(coupon);
    }

    @Override
    public Coupon selectCouponById(Integer id) {
        return couponMapper.selectCouponById(id);
    }

    @Override
    public Coupon selectCouponByCode(String code) {
        // 这里接口中定义了根据优惠码查询，但Mapper中没有对应的方法，需要补充SQL查询
        // 假设数据库表中有code字段，可补充如下逻辑
        // 实际应用中需要根据具体数据库表结构和查询需求调整
        // 示例代码：
        // @Select("SELECT id, code, name, description, type, discount, minOrderAmount, expiryDate, totalCount, remainCount, status, storeId, createTime, updateTime FROM coupon WHERE code = #{code}")
        // Coupon selectCouponByCode(@Param("code") String code);
        // 然后在这里调用新定义的Mapper方法
        // return couponMapper.selectCouponByCode(code);
        // 由于当前Mapper中没有此方法，暂时返回null
        return null;
    }

    @Override
    public List<Coupon> selectCouponsByStoreId(Integer storeId) {
        return couponMapper.selectCouponByStoreId(storeId);
    }

    @Override
    public Integer updateCoupon(Coupon coupon) {
        return couponMapper.updateCouponById(coupon);
    }

    @Override
    public Integer deleteCouponById(Integer id) {
        return couponMapper.deleteCouponById(id);
    }
}
